﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;

namespace Comisiones.Models
{
    public class Conexion
    {
        public SqlConnection connection { get; set; }

        public bool AbrirConexion()
        {
            try
            {
                string cadenaConexion = System.Configuration.ConfigurationManager.ConnectionStrings["conexionPrincipal"].ToString();
                connection = new SqlConnection(cadenaConexion);
                connection.Open();
                //MessageBox.Show("conexion a la base de datos sql server exitosa", "SAD aviso");
                return true;
            }
            catch (SqlException)
            {
                //MessageBox.Show("No es posible conectarse a la base de datos.")
                return false;
            }
        }

        public void CerrarConexion()
        {
            try
            {
                connection.Close();
            }
            catch (SqlException)
            {
                return;
            }
        }

        public SqlDataReader EjecutarReader(String consulta)
        {
            SqlDataReader dataReader = null;
            AbrirConexion();
            try
            {
                SqlCommand command = connection.CreateCommand();
                command.CommandText = consulta;
                dataReader = command.ExecuteReader();
                // CerrarConexion();
                return dataReader;
            }
            catch (Exception)
            {
                CerrarConexion();
                return dataReader;
            }
        }


        public SqlDataReader EjecutarReader2(SqlCommand comando)
        {
            SqlDataReader dataReader = null;
            AbrirConexion();
            try
            {
                dataReader = comando.ExecuteReader();
                // CerrarConexion();
                return dataReader;
            }
            catch (Exception)
            {
                CerrarConexion();
                return dataReader;
            }


        }

        public void EjecutarComando(SqlCommand command)
        {
            AbrirConexion();
            try
            {
                command.ExecuteNonQuery();
                CerrarConexion();
            }
            catch (SqlException)
            {
                CerrarConexion();
                return;
            }
            CerrarConexion();
        }
    }
}